//
//  ST_JVImagePickerController.swift
//  JVPhotoPicker-Example
//
//  Created by mac on 2019/11/12.
//  Copyright © 2019 mac. All rights reserved.
//

import UIKit
import SnapKit
import TZImagePickerController
import SwifterSwift
import SwiftyAttributes


let ST_JVScreenWidth = UIScreen.main.bounds.width

let ST_JVScreenHeight = UIScreen.main.bounds.height


let ST_JViPhoneXSeries:Bool = {
    
    if ScreenHeight > 736{
        return true
    }
    
    return false
}()

let ST_JVStatusBarHeight:CGFloat = {
    if ST_JViPhoneXSeries {
        return 44
    }else{
        return 20
    }
}()

enum ST_JVAlbumPickerStyle {
    case all,image,video
}


class ST_JVImagePickerController: UIViewController {

     override func viewDidLoad() {
        super.viewDidLoad()

        
        
        view.backgroundColor = Color.white
        view.addSubview(header)
        header.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(picker_style != .all ? 115-44 : 115)
            make.top.equalToSuperview().offset(ST_JVStatusBarHeight)
        }
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(header.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        view.addSubview(empty_label)
        empty_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(collectionView).offset(-40)
        }
        
        
        self.header.switch_tab_closure = {[weak self] in
            
            guard let strongSelf  = self else{return}
             
            strongSelf.display_video = !strongSelf.display_video
            
            strongSelf.fetch_photos()
            
        }
        
        self.header.select_album_closure = {[weak self] in
            
            guard let strongSelf  = self else{return}
             
            strongSelf.addChild(strongSelf.select_album_controller)
            strongSelf.view.addSubview(strongSelf.select_album_controller.view)
            strongSelf.select_album_controller.view.snp.makeConstraints { (make) in
                make.left.right.bottom.equalToSuperview()
                make.top.equalTo(strongSelf.header).offset(70)
            }
        }
        
        self.header.cancel_select_album_closure = {[weak self] in
            
            self?.select_album_controller.removeFromParent()
            self?.select_album_controller.view.removeFromSuperview()
            
        }
        
        self.header.finished_closure = { [weak self] in
            
            guard let assets = self?.tz_image_picker_vc.selectedAssets as? [TZAssetModel] else{
                return
            }
            
            self?.show_indeterminate_h_u_d()
            
            back_thread_execute {
                
                var imageArray = [(identifier:String,image:UIImage)]()
                
                for ast in assets{
                    
                    var willWait = true
                    
                    TZImageManager().getOriginalPhotoData(with: ast.asset) { (data, info, f) in
                        
                        guard let d = data , let img = UIImage.sd_tz_animatedGIF(with: d) else{
                            
                            imageArray.append((ast.asset.localIdentifier,UIImage()))
                        
                            willWait = false
                            
                            return
                        }
                        
                        print("拼接视频的image size:",img.size)
                        
                        imageArray.append((ast.asset.localIdentifier,img))
                        
                        willWait = false
                        
                    }
                    
                    while willWait {
                        usleep(500)
                    }
                }
                main_thread_execute {
                   
                   self?.hidden_indeterminate_h_u_d()
                    
                    if imageArray.count < 1{
                        return
                    }
                    
                    self?.picker_images_closure?(imageArray)
                    
                    self?.goback_previous_controller()
               }
                
                
                
            }
            
        }
        
        
        TZImageManager().pickerDelegate = self
        
        if !TZImageManager().authorizationStatusAuthorized(){
            
            if PHPhotoLibrary.authorizationStatus() == .notDetermined{
                
                authorized_timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(observe_authrization_status_change), userInfo: nil, repeats: false)
                
            }else{
                user_denied_authorization()
            }
        }else{
            
            switch_to(album: nil)
        }
        
    }
    
    
//    MARK: - Method
    fileprivate func user_denied_authorization(){
        
        
        
        if picker_style == .video{
            //RegisterStepManager.shared.uploadMediaStep = 5403
        }else{
            //RegisterStepManager.shared.uploadMediaStep = 4403
        }
        
        denied_view.removeFromSuperview()
        view.addSubview(denied_view)
        denied_view.snp.makeConstraints { (make) in
            make.edges.equalTo(collectionView)
        }
    }
    
    func switch_to(album:TZAlbumModel?){
        
        denied_view.removeFromSuperview()
        
        if picker_style == .video{
            //RegisterStepManager.shared.uploadMediaStep = 5402
        }else{
            //RegisterStepManager.shared.uploadMediaStep = 4402
        }
        
        if let exist = album {
            
            self.current_album = exist
            
            self.header.update_album_name(name: exist.name)
            
            self.fetch_photos()
            
            return
        }
        
        if picker_style == .video{
            self.header.update_album_name(name: "所有视频")
        }else{
            self.header.update_album_name(name: "所有照片")
        }
        
        
        TZImageManager().getCameraRollAlbum(true, allowPickingImage: true, needFetchAssets: false) { (reAlbum) in
            
            self.current_album = reAlbum
            
            self.fetch_photos()
        }
        
        
    }
    
    
    @objc func observe_authrization_status_change(){
        
        authorized_timer?.invalidate()
        authorized_timer = nil
        
        if PHPhotoLibrary.authorizationStatus() == .notDetermined{
            
            authorized_timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(observe_authrization_status_change), userInfo: nil, repeats: false)
            
            return
        }
        
        if TZImageManager().authorizationStatusAuthorized(){
            
            switch_to(album: nil)
        }else{
            user_denied_authorization()
        }
    }
    
    fileprivate func fetch_photos(){
        
      
        
        guard let result = current_album?.result else{ return }
        
        
        TZImageManager().getAssetsFrom(result, allowPickingVideo: self.display_video, allowPickingImage: !self.display_video) { (list) in
            

            guard let array =  list else{
                return
            }
                       
            print("多少张图片呢？",array.count)
            
            self.data_array = array.filter({ (zAsset) -> Bool in
                            
                if zAsset.type == TZAssetModelMediaType.init(3),let timeLength = zAsset.timeLength{
                    
                    let timeArray = timeLength.components(separatedBy: ":")
                    
                    var timeSeconds = 0.float
                    for (idx,item) in timeArray.reversed().enumerated(){
                        if let value = item.float(){
                            timeSeconds += value * powf(60, idx.float)
                        }
                    }
                    if  timeSeconds < 5 || timeSeconds > 60{
                        return false
                    }
                }
                
                
                
                
//                print("每次符合的id还不一样？",zAsset.asset.localIdentifier,"---Normal_IDS:",self.normal_selected_id_array)
                
                if self.normal_selected_id_array.contains(zAsset.asset.localIdentifier){
                        
                        zAsset.isSelected = true
                        
                        if self.tz_image_picker_vc.selectedAssetIds.contains(zAsset.asset.localIdentifier) == false{
                            
                            self.tz_image_picker_vc.selectedAssetIds.add(zAsset.asset.localIdentifier)
                            
                            self.tz_image_picker_vc.selectedAssets.add(zAsset)
                            
                        }
                    }
                
                return true
            })
           
           self.collectionView.reloadData()
            
            if array.count < 1{
                
                self.empty_label.isHidden = false
                
                self.empty_label.attributedText = self.display_video ? self.empty_video_attribute : self.empty_photos_attribute
                
            }else{
                
                self.empty_label.isHidden = true
            }
            
        }
    }
//    MARK: - outSide Properties
//
//    var outputVideoPathClosure:((String)->())?
    
    
    var picker_images_closure:(([(identifier:String,image:UIImage)])->())?
    
    var picker_video_closure:((URL,Double)->())?
    
//    MARK: - Properties
    
    var close_closure:(()->())?
    
    var picker_style = ST_JVAlbumPickerStyle.all
    
    fileprivate lazy var header:ST_JVImagePickerHeader = {
       let control = ST_JVImagePickerHeader()
        control.close_closure = {[weak self] in
            
            //RegisterStepManager.shared.uploadMediaStep = 4404
            
            self?.close_closure?()
        }
        control.picker_style = picker_style
        return control
    }()
    
    fileprivate lazy var select_album_controller:ST_JVAlbumListController = {
       let control = ST_JVAlbumListController()
        control.selectedAlbumClosure = {[weak self] ab in
            self?.switch_to(album: ab)
            self?.header.set_center_btn_state_normal()
        }
        return control
    }()
    
    fileprivate lazy var display_video:Bool = {
        if picker_style == .video{
            return true
        }
        return false
    }()
    
    fileprivate var current_album:TZAlbumModel?
    
    fileprivate var data_array = [TZAssetModel]()
    
    fileprivate var authorized_timer:Timer?
    
    fileprivate let rowCount = 4
    
    fileprivate let minimum_spacing = 2.cgFloat
    
    fileprivate lazy var itemWidth:CGFloat = {
        
        return (ST_JVScreenWidth-minimum_spacing*(rowCount-1).cgFloat)/rowCount.cgFloat
        
    }()
        
    
    fileprivate lazy var denied_view: ST_JVDeniedPhotoAuthorizationView = ST_JVDeniedPhotoAuthorizationView()
    fileprivate lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
//        layout.scrollDirection = UICollectionView.ScrollDirection.horizontal
        layout.itemSize = CGSize.init(width: itemWidth, height: itemWidth)
        //        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = minimum_spacing
        layout.minimumInteritemSpacing = minimum_spacing

        let collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
        
        collection.backgroundColor = Color.white
        
        collection.register(cellWithClass: TZAssetCell.self)
        //        collection.alwaysBounceVertical = true
        collection.delegate = self
        
        collection.dataSource = self
        
        return collection
    }()
    
    fileprivate lazy var empty_video_attribute:NSAttributedString = {
        return "相册中没有视频".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)),Attribute.textColor(UIColor.init(hex: 0x000000)!)])
    }()
    
    fileprivate lazy var empty_photos_attribute:NSAttributedString = {
        return "相册中没有图片".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)),Attribute.textColor(UIColor.init(hex: 0x000000)!)])
    }()
    
    fileprivate lazy var empty_label:UILabel = {
       let control = UILabel()
        control.isHidden = true
        control.textAlignment = .center
        return control
    }()
//    MARK: - 选中
//    fileprivate var selectedModels = [TZAssetModel]()
//
//    fileprivate var selectedModelIdArray = [String]()
    
    var maxImagesCount = 9{
        didSet{
            tz_image_picker_vc.maxImagesCount = self.maxImagesCount
        }
    }
    
    var normal_selected_id_array = [String](){
        didSet{
            
            print("所有外部选中ID:",normal_selected_id_array)
        }
    }
    
    
    
    fileprivate lazy var tz_image_picker_vc:TZImagePickerController = {
        let obj = TZImagePickerController()
        obj.showSelectedIndex = true
        obj.maxImagesCount = self.maxImagesCount
        obj.showPhotoCannotSelectLayer = true
        obj.allowPreview = true
        obj.photoSelImage = UIImage.init(color: UIColor.init(hex: 0xFEC207)!, size: CGSize.init(width: 24, height: 24)).withRoundedCorners()
        return obj
    }()
    
    fileprivate var previewRect = CGRect.zero
    
    fileprivate var preview_image_view:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.imageView?.contentMode = .scaleAspectFit
        control.backgroundColor = Color.black
        control.clipsToBounds = true
        control.addTarget(self, action: #selector(dismiss_preview_image_view_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
//    MARK: - Event
    @objc func dismiss_preview_image_view_handle(){
        
        UIView.animate(withDuration: 0.25, animations: {
            
            self.preview_image_view.frame = self.previewRect
            
        }) { (f) in
            
            self.preview_image_view.removeFromSuperview()
        }
        
        
    }
    
    func fresh_right_item_bar_status(){
        
        self.header.update_right_btn_status(count: tz_image_picker_vc.selectedAssetIds.count)
        
    }
    
    func push_edit_video_handle(asset:TZAssetModel){
        
        self.show_indeterminate_h_u_d()
        
        let options = PHVideoRequestOptions()
        
        options.version = .original
        options.deliveryMode = .automatic
        options.isNetworkAccessAllowed = true
        
        
        PHCachingImageManager().requestAVAsset(forVideo: asset.asset, options: options) { (avAsset, audioMix, info) in
            
            guard let tempAsset = avAsset as? AVURLAsset else{
                return
            }
            
            
            
            main_thread_execute {

               self.hidden_indeterminate_h_u_d()
               
                self.picker_video_closure?(tempAsset.url, tempAsset.duration.seconds)
                
                self.goback_previous_controller()
           }
            
        }
        
        
//        TZImageManager().getVideoOutputPath(with: asset.asset, presetName: AVAssetExportPresetHighestQuality, success: { (path) in
//
//            guard let videoPath = path else{return}
//
//            main_thread_execute {
//
//                self.hidden_indeterminate_h_u_d()
//
//                let vc = CutVideoController()
//
//                vc.videoPath = videoPath
//
//                GlobalPresent(toController: vc)
//
//            }
//
//
//        }) { (code, err) in
//
//            ToastHud(text: "获取视频错误" , view: self.view)
//
//        }
        
        
        
    }
    
    func alert_max_select_images(){
        
        show_alert_with_title(title: "最多选择\(tz_image_picker_vc.maxImagesCount)张图片")
    }
    
    
    func show_alert_with_title(title:String){
        
        let alert = UIAlertController.init(title: "提示", message: title, preferredStyle: UIAlertController.Style.alert)
        
        
        alert.addAction(title: "ok", style: UIAlertAction.Style.default, isEnabled: true) { (action) in
            
        }
        
        self.present(alert, animated: true, completion: nil)
        
    }
    

}

extension ST_JVImagePickerController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: TZAssetCell.self, for: indexPath)
        
        cell.photoDefImage = tz_image_picker_vc.photoDefImage;
        cell.photoSelImage = tz_image_picker_vc.photoSelImage;
        
        let model = self.data_array[indexPath.row]
        
        cell.model = model
        
        if (model.isSelected && tz_image_picker_vc.showSelectedIndex) {
        
            let foundIdx = tz_image_picker_vc.selectedAssetIds.index(of: model.asset.localIdentifier)
            
            cell.index = foundIdx + 1
        }

        if !self.display_video{

            cell.showSelectBtn = tz_image_picker_vc.showSelectBtn;
            cell.allowPreview = tz_image_picker_vc.allowPreview;
        }else{
            cell.showSelectBtn = false
            cell.allowPreview = false
        }
        
        if (tz_image_picker_vc.selectedAssetIds.count >= tz_image_picker_vc.maxImagesCount && tz_image_picker_vc.showPhotoCannotSelectLayer && !model.isSelected) {
            cell.cannotSelectLayerButton.backgroundColor = tz_image_picker_vc.cannotSelectLayerColor;
            cell.cannotSelectLayerButton.isHidden = false;
        } else {
            cell.cannotSelectLayerButton.isHidden = true;
        }
      
        
        weak var weakCell = cell
        
        weak var weakModel = model
        
        cell.didSelectPhotoBlock = {[weak self] isSelected in
            
            guard let strongSelf = self else { return  }
            
            guard let strongModel = weakModel else { return  }
            
            guard let strongCell = weakCell else { return  }
            
            if strongSelf.display_video{
                
                strongSelf.push_edit_video_handle(asset: strongModel)
                
                strongSelf.header.update_right_btn_status(count: 0)
                
                return
            }
            
            // 1. cancel select / 取消选择
            if (isSelected) {
                strongCell.selectPhotoButton.isSelected = false
                
                strongModel.isSelected = false
                
                strongSelf.tz_image_picker_vc.selectedAssetIds.remove(strongModel.asset.localIdentifier)
                
                strongSelf.tz_image_picker_vc.selectedAssets.remove(strongModel)
             
                if (strongSelf.tz_image_picker_vc.showSelectedIndex || strongSelf.tz_image_picker_vc.showPhotoCannotSelectLayer) {
                    
                    NotificationCenter.default.post(name: NSNotification.Name.init("TZ_PHOTO_PICKER_RELOAD_NOTIFICATION"), object: strongSelf.tz_image_picker_vc, userInfo: nil)
                    
                }
                
            } else {
                
                // 2. select:check if over the maxImagesCount / 选择照片,检查是否超过了最大个数的限制
                
                if strongSelf.tz_image_picker_vc.selectedAssetIds.count >= strongSelf.tz_image_picker_vc.maxImagesCount{
                    
                    strongSelf.alert_max_select_images()
                    
                }else{
                    
                    weakCell?.selectPhotoButton.isSelected = true
                    weakModel?.isSelected = true
                    
                    strongSelf.tz_image_picker_vc.selectedAssetIds.add(strongModel.asset.localIdentifier)
                    strongSelf.tz_image_picker_vc.selectedAssets.add(strongModel)
                    
                    NotificationCenter.default.post(name: NSNotification.Name.init("TZ_PHOTO_PICKER_RELOAD_NOTIFICATION"), object: strongSelf.tz_image_picker_vc, userInfo: nil)
                    
                }
            }
            
            strongSelf.fresh_right_item_bar_status()
            
        }
        
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        if display_video{
            
            self.push_edit_video_handle(asset: data_array[indexPath.item])
            
            return
            
        }else{
            
            
            let m = data_array[indexPath.item]
            
            
            guard let cell = collectionView.cellForItem(at: indexPath) else{
                return
            }
            
            let rect =  collectionView.convert(cell.frame, to: nil)
            
            preview_image_view.frame = rect
            
            previewRect = rect
            
            self.view.addSubview(preview_image_view)
            
            TZImageManager().getOriginalPhotoData(with: m.asset) {[weak self] (data, info, f) in
                
                guard let d = data , let img = UIImage.init(data: d) else{
                    return
                }
                
                print("拼接视频的image size:",img.size)
                
                self?.preview_image_view.setImageForAllStates(img)
                
                UIView.animate(withDuration: 0.25, animations: {
                    
                    self?.preview_image_view.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: ST_JVScreenWidth, height: ST_JVScreenHeight))
                    
                }) { (f) in
                    
                }
            }
            
            
        }
        
        
    }
    
}


extension ST_JVImagePickerController:TZImagePickerControllerDelegate{
    
    
    func is_asset_can_select(_ asset: PHAsset!) -> Bool {
        
        return true
    }
    
}

